介紹
外觀模式將一系列的操作藏在介面後,方便用戶統一操作。
舉個例子: 到家後會開電燈、開電視、開冷氣。出門前會關冷氣、關電視、關電燈。每天進出門要按那麼多按鈕,不如將這些操作編進遙控器的ON、OFF按鈕,進門後按On按鈕電器全開,出門前按Off按鈕電器全關。
C++範例
#include <iostream>
class Light
{
public:
void LightOn()
{
std::cout << "Light is on" << std::endl;
}
void LightOff()
{
std::cout << "Light is off" << std::endl;
}
};
class TV
{
public:
void TVOn()
{
std::cout << "TV is on" << std::endl;
}
void TVOff()
{
std::cout << "TV is off" << std::endl;
}
};
class AirConditioner
{
public:
void ACOn()
{
std::cout << "Air conditioner is on" << std::endl;
}
void ACOff()
{
std::cout << "Air conditioner if off" << std::endl;
}
};
class HouseFacade
{
public:
HouseFacade() {}
void AllOn()
{
m_light.LightOn();
m_tv.TVOn();
m_ac.ACOn();
}
void AllOff()
{
m_light.LightOff();
m_tv.TVOff();
m_ac.ACOff();
}
private:
Light m_light;
TV m_tv;
AirConditioner m_ac;
};
int main()
{
HouseFacade hf;
// 出門前,關閉電器
hf.AllOff();
// 在外...
//
// 到家後,開啟電器
hf.AllOn();
return 0;
}
Output:
Light is off
TV is off
Air conditioner if off
Light is on
TV is on
Air conditioner is on